/*
 * Copyright 2023 Hu Zheng <huzheng001@gmail.com>
 *
 * This file is part of StarDict.
 *
 * StarDict is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * StarDict is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with StarDict.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "stardict_multi_cmd.h"
#include <glib/gi18n.h>
#include <gtk/gtk.h>
#include <stdlib.h>
#include <cstring>
#include <memory>
#include <list>
#include <string>

static const StarDictPluginSystemInfo *plugin_info = NULL;
static const StarDictPluginSystemService *plugin_service;
static IAppDirs* gpAppDirs = NULL;

static std::list<std::string> Command_List;

/* concatenate path1 and path2 inserting a path separator in between if needed. */
static std::string build_path(const std::string& path1, const std::string& path2)
{
	std::string res;
	res.reserve(path1.length() + 1 + path2.length());
	res = path1;
	if(!res.empty() && res[res.length()-1] != G_DIR_SEPARATOR)
		res += G_DIR_SEPARATOR_S;
	if(!path2.empty() && path2[0] == G_DIR_SEPARATOR)
		res.append(path2, 1, std::string::npos);
	else
		res.append(path2);
	return res;
}

static std::string get_cfg_filename()
{
	return build_path(gpAppDirs->get_user_config_dir(), "multi_cmd.cfg");
}

static void multi_lookup(const char *text, char ** &dict_name, char **** &ppppWord, char ***** &pppppWordData, bool &bFound)
{
	size_t dict_count = 0;
	for(std::list<std::string>::const_iterator it = Command_List.begin(); it != Command_List.end(); ++it) {
		if (it->empty()) {
			continue;
		}
		std::string definition;
		bool found = true;
		FILE *pf = popen(it->c_str(), "r"); // Always return NOT NULL! But fread() == 0
		if (!pf) {
			found = false;
		} else {
			char buffer[2048];
			size_t len;
			while (true) {
				len = fread(buffer, 1, sizeof(buffer), pf);
				if (len <= 0)
					break;
				definition.append(buffer, len);
			}
			pclose(pf);
			if (definition.empty()) {
				found = false;
			} else {
				size_t length1;
				while (true) {
					length1 = definition.length() -1;
					if ((definition[length1] == '\n') || (definition[length1] == ' ')) {
						definition.resize(length1, '\0');
					} else {
						break;
					}
				}
			}
		}
		std::string pango;
		if (found) {
			plugin_service->terminal2pango(definition.c_str(), pango);
		} else {
			pango = _("<b><span foreground=\"red\">");
			pango += *it;
			pango += _("</span> program is not found! Please install it!</b>");
		}
		dict_count++;
		std::string dict_name1 = _("Multi Command - ");
		dict_name1 += it->c_str();
		dict_name = (gchar **)g_realloc(dict_name, sizeof(gchar *)*dict_count);
		ppppWord = (gchar ****)g_realloc(ppppWord, sizeof(gchar *)*dict_count);
		pppppWordData = (gchar *****)g_realloc(pppppWordData, sizeof(gchar **)*(dict_count));
		dict_name[dict_count-1] = (gchar *)g_strdup(dict_name1.c_str());
		ppppWord[dict_count-1] = (gchar ***)g_malloc(sizeof(gchar *)*2);
		ppppWord[dict_count-1][0] = (gchar **)g_strdup(text);
		ppppWord[dict_count-1][1] = NULL;
		pppppWordData[dict_count-1] = (gchar ****)g_malloc(sizeof(gchar **)*(1));
		pppppWordData[dict_count-1][0] = (gchar ***)g_malloc(sizeof(gchar *)*2);
		pppppWordData[dict_count-1][0][0] =  (gchar **)plugin_service->build_dictdata('g', pango.c_str());
		pppppWordData[dict_count-1][0][1] = (gchar **)NULL;
	}
    if (dict_count > 0) {
    	dict_name = (gchar **)g_realloc(dict_name, dict_count+1);
    	*dict_name[dict_count] = '\0';
        bFound = true;
    }
}

void on_cmd_path_defaultbutton_clicked(GtkWidget *widget, GtkTextBuffer *buffer)
{
	gtk_text_buffer_set_text(buffer, "toilet\nbanner\ncowsay\nrig\nsl\ncmarix\naafire\n", -1);
}

void Command_List_to_str(std::string &Command_List_str)
{
	for(std::list<std::string>::const_iterator it = Command_List.begin(); it != Command_List.end(); ++it) {
		if (it->empty()) {
			continue;
		}
		Command_List_str += it->c_str();
        Command_List_str += '\n';
    }
}

void Command_List_to_str2(std::string &Command_List_str2)
{
	for(std::list<std::string>::const_iterator it = Command_List.begin(); it != Command_List.end(); ++it) {
		if (it->empty()) {
			continue;
		}
		Command_List_str2 += it->c_str();
        Command_List_str2 += "\\\\n";
    }
}

static void configure()
{
	GtkWidget *window = gtk_dialog_new_with_buttons(_("Multi Command configuration"), GTK_WINDOW(plugin_info->pluginwin), GTK_DIALOG_MODAL, GTK_STOCK_OK, GTK_RESPONSE_ACCEPT, NULL);
#if GTK_MAJOR_VERSION >= 3
	GtkWidget *vbox = gtk_box_new(GTK_ORIENTATION_VERTICAL, 5);
#else
	GtkWidget *vbox = gtk_vbox_new(false, 5);
#endif
	GtkWidget *label = gtk_label_new(_("Multi command paths:"));
	gtk_misc_set_alignment(GTK_MISC(label), 0, .5);
	gtk_box_pack_start(GTK_BOX(vbox), label, false, false, 0);

	GtkWidget *hbox2;
#if GTK_MAJOR_VERSION >= 3
	hbox2 = gtk_box_new(GTK_ORIENTATION_HORIZONTAL, 6);
#else
	hbox2 = gtk_hbox_new(FALSE, 6);
#endif
	gtk_box_pack_start(GTK_BOX(vbox), hbox2, FALSE, FALSE, 0);

	GtkWidget *cmd_textview = gtk_text_view_new();
	gtk_widget_set_size_request(cmd_textview, 240, 240);
	gtk_text_view_set_wrap_mode(GTK_TEXT_VIEW(cmd_textview), GTK_WRAP_CHAR);
	GtkWidget *scrolled_window = gtk_scrolled_window_new(NULL, NULL);
	gtk_scrolled_window_set_shadow_type (GTK_SCROLLED_WINDOW (scrolled_window), GTK_SHADOW_ETCHED_IN);
	gtk_scrolled_window_set_policy (GTK_SCROLLED_WINDOW (scrolled_window), GTK_POLICY_AUTOMATIC, GTK_POLICY_AUTOMATIC);
	gtk_box_pack_start(GTK_BOX(hbox2), scrolled_window, false, false, 0);
	gtk_container_add(GTK_CONTAINER(scrolled_window), cmd_textview);
	std::string Command_List_str;
    Command_List_to_str(Command_List_str);
	GtkTextBuffer *buffer = gtk_text_view_get_buffer(GTK_TEXT_VIEW(cmd_textview));
	gtk_text_buffer_set_text(buffer, Command_List_str.c_str(), -1);

	GtkWidget *button = gtk_button_new_with_mnemonic(_("_Default"));
	g_signal_connect (G_OBJECT (button), "clicked", G_CALLBACK (on_cmd_path_defaultbutton_clicked), buffer);
	gtk_box_pack_start(GTK_BOX(hbox2), button, FALSE, FALSE, 0);

	gtk_widget_show_all(vbox);
	gtk_container_add (GTK_CONTAINER (gtk_dialog_get_content_area(GTK_DIALOG(window))), vbox);
	gtk_dialog_run(GTK_DIALOG(window));
	GtkTextIter start_iter, end_iter;
	gtk_text_buffer_get_start_iter(buffer, &start_iter);
	gtk_text_buffer_get_end_iter(buffer, &end_iter);
	gchar *text = gtk_text_buffer_get_text(buffer, &start_iter, &end_iter, FALSE);
    if (Command_List_str != text) {
    	gchar *p1, *p2;
	    p2 = text;
	    Command_List.clear();
	    while (true) {
	    	p1 = strchr(p2, '\n');
	    	if (!p1) {
	    		break;
	    	}
            if (p1 > p2) {
        	    std::string cmd_path(p2, p1-p2);
   	        	Command_List.push_back(cmd_path);
            }
	    	p2 = p1 + 1;
	    }
        if (*p2 != '\0') {
            std::string cmd_path(p2);
	    	Command_List.push_back(cmd_path);
        }
        std::string Command_List_str2;
        Command_List_to_str2(Command_List_str2);
		gchar *data = g_strdup_printf("[multi_cmd]\ncmds=%s\n", Command_List_str2.c_str());
		std::string res = get_cfg_filename();
		g_file_set_contents(res.c_str(), data, -1, NULL);
		g_free(data);
    }
	g_free(text);
	gtk_widget_destroy (window);
}

bool stardict_plugin_init(StarDictPlugInObject *obj, IAppDirs* appDirs)
{
	g_debug(_("Loading Multi Command plug-in..."));
	if (strcmp(obj->version_str, PLUGIN_SYSTEM_VERSION)!=0) {
		g_print(_("Error: Multi Command plugin version doesn't match!\n"));
		return true;
	}
	obj->type = StarDictPlugInType_VIRTUALDICT2;
	obj->info_xml = g_strdup_printf("<plugin_info><name>%s</name><version>1.0</version><short_desc>%s</short_desc><long_desc>%s</long_desc><author>Hu Zheng &lt;huzheng001@gmail.com&gt;</author><website>http://stardict-4.sourceforge.net</website></plugin_info>", _("Multi Command"), _("Multi Command virtual dictionary."), _("Show Multi Command."));
	obj->configure_func = configure;
	plugin_info = obj->plugin_info;
	plugin_service = obj->plugin_service;
	gpAppDirs = appDirs;

	return false;
}

void stardict_plugin_exit(void)
{
	gpAppDirs = NULL;
}

bool stardict_virtualdict2_plugin_init(StarDictVirtualDict2PlugInObject *obj)
{
	obj->multi_lookup_func = multi_lookup;
	obj->total_dict_name = _("Multi Command");
	obj->author = _("Hu Zheng");
	obj->email = _("huzheng001@gmail.com");
	obj->website = _("http://www.huzheng.org");
	obj->date = _("2023.12.22");

	std::string res = get_cfg_filename();
	if (!g_file_test(res.c_str(), G_FILE_TEST_EXISTS)) {
		Command_List.push_back("toilet");
		Command_List.push_back("banner");
		Command_List.push_back("cowsay");
		Command_List.push_back("rig");
		Command_List.push_back("sl");
		Command_List.push_back("cmarix");
		Command_List.push_back("aafire");

		g_file_set_contents(res.c_str(), "[multi_cmd]\ncmds=toilet\\\\nbanner\\\\ncowsay\\\\nrig\\\\nsl\\\\ncmarix\\\\naafire\\\\n\n", -1, NULL);
	} else {
    	GKeyFile *keyfile = g_key_file_new();
    	g_key_file_load_from_file(keyfile, res.c_str(), G_KEY_FILE_NONE, NULL);
    	gchar *str = g_key_file_get_string(keyfile, "multi_cmd", "cmds", NULL);
    	if (str) {
            gchar *p1, *p2;
	        p2 = str;
       	    while (true) {
       		    p1 = strstr(p2, "\\n");
       		    if (!p1) {
    		    	break;
    		    }
    		    std::string cmd_path(p2, p1-p2);
    		    Command_List.push_back(cmd_path);
    		    p2 = p1 + 2;
    	    }
		    g_free(str);
	    }
    	g_key_file_free(keyfile);
    }
	g_print(_("Multi Command plug-in \033[31m[loaded]\033[0m.\n"));
	return false;
}
